package TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoClient {
    private Socket clientSocket = null;

    public TCPEchoClient(String serverIP, int serverPort) throws IOException {
        this.clientSocket = new Socket(serverIP, serverPort);
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scannerNet = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true) {
                if (!scanner.hasNext()) {
                    break;
                }
                String request = scanner.next();
                writer.println(request);
                writer.flush();//刷新缓冲区
                String response = scannerNet.next();
                System.out.println(response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
       TCPEchoClient tcpEchoClient = new TCPEchoClient("127.0.0.1", 9090);
       tcpEchoClient.start();
    }
}
